#include "client.h"

int main() {
    int clientfd = tcpConnect("127.0.0.1", 8080);

    char buf[512] = {0};

    login(clientfd);

    // 使用select进行监听
    fd_set rdset;
    train_t t;
    while (1) {
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO, &rdset);
        FD_SET(clientfd, &rdset);

        int nready = select(clientfd + 1, &rdset, NULL, NULL, NULL);
        if (FD_ISSET(STDIN_FILENO, &rdset)) {
            // 读取标准输入中的数据
            memset(buf, 0, sizeof(buf));
            int ret = read(STDIN_FILENO, buf, sizeof(buf));
            if (0 == ret) {
                printf("byebye.\n");
                break;
            }
            memset(&t, 0, sizeof(t));
            // 解析命令行
            buf[strlen(buf) - 1] = '\0';
            parseCommand(buf, strlen(buf), &t);

            // 发送命令
            sendn(clientfd, &t, 4 + 4 + t.len);

            // 检查命令类型并执行相应操作
    /*          if (t.type == CMD_TYPE_PUTS) {
                printf("执行 puts 命令。\n");
                Sendfile(clientfd, t.buff);
            }
        } else if (FD_ISSET(clientfd, &rdset)) {
            // 接收命令类型
            CmdType cmd = t.type;
            if (cmd == CMD_TYPE_GETS) {
                printf("excute gets.\n");
                if (recvfile(clientfd) == -1) {
                    perror("recvfile failed.");
                    break;
                }
            } else {
                    // 处理其他命令
                    recv(clientfd, buf, sizeof(buf), 0);
                    printf("接收: %s\n", buf);
                }
    */

            switch(t.type)
            {
            case CMD_TYPE_PUTS:
                putsHandle(clientfd,&t);  break;
            case CMD_TYPE_GETS:
                getsHandle(clientfd,&t);  break;
            default:
                continue;
            }


        } else if(FD_ISSET(clientfd, &rdset)) {
            recv(clientfd, buf, sizeof(buf), 0);
            printf("接收: %s\n", buf);



        }
    }
    close(clientfd);
    return 0;
}

